<?php
/**
 * Connect.class.php
 *
 * @author 周剑锋 <camfee@foxmail.com>
 *
 * $Id$
 */

namespace controls\MobileApi\Passport;

use MobileApi\ApiBase;
use Passport\Connect as PConnect;
use MobileApi\Passport;
use Passport\Login;
use Center\User as CUser;
use Passport\ConnectBase;
use Passport\Register;


/**
 * 通行证- 第三方用户接口
 *
 * @package Passport
 * @author  周剑锋 <camfee@foxmail.com>
 * @since   1.0.0 2017-08-31
 */
class Connect extends ApiBase
{
    /**
     * 第三方用户登录
     *
     * <pre>
     * POST
     *      code:   第三方开放平台Authorization Code，必选, 微信:Authorization Code QQ、微博:Access_Token
     *      type:   帐号类型ID,                      可选, 20：新浪微博|22：QQ|26：app微信|27:网页微信 默认为27
     * </pre>
     *
     * @return void|string 返回JSON数据
     *
     * <pre>
     * {
     *   "Status": 200,
     *   "Result": {
     *        'Auth': '认证字符串',
     *        'UserId': 用户ID,
     *        'UserNick': '用户昵称',
     *        'Mobile': '手机号码',
     *        'HeadUrl': '用户头像',
     *        'CityId': 0, // 注册城市id
     *        'CityName': '', // 注册城市
     *        'RealName': '', // 姓名
     *        'IdCode': '', // 身份证号
     *        'Sex': 0, //  性别 0未知，1 男，2 女
     *        'BirthDay': '', // 生日
     *        'JCoinNum': 0, // 金果数
     *        "IsShop": 1, // 是否是商家 1：是 0：否
     * }
     *
     * 异常状态
     * 201: 缺少参数code
     * 202: 类型ID错误
     * 203: 授权失败
     * 204: 获取用户授权信息失败
     * 205: 注册失败
     * 206: openid获取失败!
     * 207: 账号已经被禁止
     * 208: 网络繁忙，请稍后再试！
     * </pre>
     */
    public function login()
    {
        $code = trim($_POST['code']);
        $type = intval($_POST['type']);
        if (empty($type)) {
            $type = ConnectBase::PLATFORM_WEIXIN_WEB;
        }

        if (empty($code)) {
            $this->output(201, '缺少参数code');
        }
        if (!in_array($type, ConnectBase::$allow_types)) {
            $this->output(202, '类型ID错误');
        }

        $data = ConnectBase::getOpenId($code, $type);
        if (empty($data['OpenId'])) {
            $this->output(203, '授权失败！');
        }
        $openid = $data['OpenId'];
        $con = PConnect::getUserByOpenId($openid, $type);
        if (!empty($con['UserId'])) { // 登录
            $uid = $con['UserId'];
        } elseif ($con['status'] == 203) { // 注册通行证用户
            $data1 = ConnectBase::getUserInfo($data['AccessToken'], $openid, $type);
            if (empty($data1)) {
                $this->output(204, '获取用户授权信息失败！');
            }
            $data = array_merge($data, $data1);
            if ($GLOBALS['g_appid'] == MOBILE_APPID_ANDROID) {
                $platform = PConnect::REG_PLATFORM_ANDROID;
            } elseif ($GLOBALS['g_appid'] == MOBILE_APPID_IPHONE) {
                $platform = PConnect::REG_PLATFORM_IPHONE;
            } else {
                $platform = PConnect::REG_PLATFORM_WAP;
            }
            $puser = Register::addUser(Register::REG_TYPE_CONNECT, [
                'UserName' => Register::getRandomName(),
                'Password' => '',
                'FromPlatform' => $platform,
                'FromProduct' => Register::REG_FROM_JINGUO,
                'FromWay' => $type
            ]);
            if (!empty($puser['UserId'])) {
                $uid = $puser['UserId'];
                PConnect::addUser($type, $puser['UserId'], $openid, $data);
            } else {
                $this->output(205, '注册失败！' . $puser['msg']);
            }
        }

        if (!empty($uid)) {
            $user = CUser::getInfoByIds($uid);
            $puserInfo = $con;
            $login_type = Passport::LOGIN_TYPE_LOGIN;
            if (empty($user['UserId'])) { // 注册本站用户
                $user = $puserInfo;
                $headUrl = CUser::crawlHeadUrl($uid, $data['Avatar']);
                debug_log('headUrl: ' . $data['Avatar']);
                if (empty($headUrl)) {
                    $log = [
                        'avatar' => $data['Avatar'],
                        'uid' => $uid,
                        'msg' => 'avatar upload failed',
                        'time' => date('Y-m-d H:i:s'),
                    ];
                    debug_log($log);
                    $headUrl = '';
                }
                $udata = [
                    'UserId' => $uid,
                    'UserNick' => $data['NickName'],
                    'Mobile' => (string)$user['Mobile'],
                    'HeadUrl' => $headUrl,
                ];
                CUser::add($udata);
                $login_type = Passport::LOGIN_TYPE_REG; // 登录|注册
            }
            $update_count = $type == ConnectBase::PLATFORM_WEIXIN_WEB ? false : true;
            Login::updateLoginInfo($uid, $update_count);
            $result = Passport::getLoginInfo($uid, $login_type);
            $this->output(200, $result);
        }
    }
}
